
import UIKit
import HandyJSON

let kLocalList = "localList"

class AISaveModel: HandyJSON{
    
    var result:[ResultList]?
    var name:String?
    var imagePath:String?
    
    required init() {}
}

class ResultList: HandyJSON{
    
    var score:String?
    var name:String?
    var baike_info:baikeInfo?
    
    required init() {}
}

class baikeInfo: HandyJSON{
    
    var baike_url:String?
    var description:String?
    
    required init() {}
}

@objcMembers class LocalMan: NSObject {
    
    @objc static let shared:LocalMan = LocalMan()
    
    func getLocalList() -> [String]{
        
        if let list:[String] = UserDefaults.standard.value(forKey: kLocalList) as? [String]{
            return list
        }
        return [String]()
    }
    
    func getAIModelList() -> [AISaveModel]{
        
        var datas = [AISaveModel]()
        let list = getLocalList()
        for jsonStr in list {
            let vo = AISaveModel.deserialize(from: jsonStr) ?? AISaveModel()
                datas.append(vo)
        }
        return datas.reversed()
    }
    
    func addAIModel(model:AISaveModel){
        
        var list = getLocalList()
        if let str = model.toJSONString() {
            list.append(str)
        }
        UserDefaults.standard.setValue(list, forKey: kLocalList)
    }
    
    func saveAD(image:UIImage) -> String{
        
        guard let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first else {
            return ""
        }
        var imageName = "\(Date.getCurrentDate(type: .img)).png"
        if let name = image.accessibilityIdentifier {
            imageName = name
        }
        let imagePath = "\(imageName)"
        let path = (documentsDirectory as NSString).appendingPathComponent(imagePath)
        if let data = image.jpegData(compressionQuality: 1.0) {
            do {
                try data.write(to: URL(fileURLWithPath: path), options: .atomic)
                print("图片保存成功")
            } catch {
                print("图片保存失败: \(error.localizedDescription)")
            }
        }
        
        return imagePath
    }
    
    func getImage(imagePath:String) -> UIImage{
        
        guard let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first else {
            return UIImage()
        }
        let path = (documentsDirectory as NSString).appendingPathComponent(imagePath)
        if let image = UIImage(contentsOfFile: path) {
            // 在这里使用读取到的 UIImage
            
            return image
        } else {
            print("图片读取失败")
        }
        return UIImage()
    }
    
}

